package com.limit.rateLimit;

import com.limit.service.TimeWindowLimit;

/**
 * @作者: 林江
 * @创建时间: 2023/12/21
 * @功能: 漏桶算法
 */
public class LeakyBucketTimeWindow implements TimeWindowLimit {
    private long start = System.currentTimeMillis(); // 当前时间的时间戳
    private int capacity = 10; // 定义漏桶的容量
    private int rate = 1; // 定义每秒钟能处理的请求数

    private long req = 5; // 漏桶中的请求，初始容量5个请求

    @Override
    public synchronized boolean limit() {
        long end = System.currentTimeMillis();
        req = Math.max(0, req - ((end - start) / 1000 * rate));
        start = end;

        if ((req + 1) <= capacity) {
            req++;
            System.out.println("请求数：" + req);
            return false;
        } else {
            return true;
        }
    }
}
